package com.banksystem.controller;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.banksystem.Jwt.JwtKit;
import com.banksystem.Util.RedisUtil;
import com.banksystem.entity.Group;
import com.banksystem.entity.userinfo;
import com.banksystem.service.Groupservice;
import com.banksystem.service.userinfoservice;

@Controller

public class IndexController {
	@Autowired
	private userinfoservice uservice;
	@Autowired
	private Groupservice gs;
	@Autowired
	private RedisUtil redis;
	/*
	 * 判断登录信息
	 */
	@RequestMapping("home")
	public String login(String username,String password,String role,HttpServletResponse response,ModelMap model,HttpServletRequest session) {
		Integer times = (Integer)redis.get(username+"times");//获取用户登录次数
		if(times==null){
			times=2;
		}
		if(times!=4){
			
			//request.getSession().removeAttribute("gname");
			userinfo user = uservice.finduser(username, password,role);
			if(user != null) {//查询用户是否存在
				redis.set(username, user);
				String token = JwtKit.getToken(username);
				Cookie cookie = new Cookie("Authorization", token);
				response.addCookie(cookie);
				if(role.equals("管理员")) {
					model.addAttribute("username", username);
					//session.setAttribute("username", username);
					session.getSession(true).setAttribute("gname", username);
					return "index-admin";
				}else {
					model.addAttribute("username", username);
					Group gr=gs.findstxxAll(username);
					session.getSession(true).setAttribute("gname", gr.getName());
					//session.setAttribute("gname", gr.getName());
					return "index-fzr";
				}
			}else {
				redis.set(username+"times", ++times, 10*2);
				model.addAttribute("model", "账号密码错误！请重新登录");
				return "login";
			}
		}
		else {
			model.addAttribute("model", "登录失败！2分钟后重新登录");
			return "login";
		}
		
	}
	/*
	 * 退出按钮
	 */
	@RequestMapping("tc")
	public String tc() {
		return "login";
	}
	/*
	 * 拦截器返回false的跳转路径
	 */
	@RequestMapping("jump")
	public @ResponseBody String jump(){
		return "false";
	}
	
}
